package com.example.demo1.servlet;

import com.example.demo1.Cake;
import com.example.demo1.CakeDB;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(name = "PurchaseServlet", urlPatterns = "/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String id = req.getParameter("id");
        if (id == null) {
            // 如果id为null，重定向到ListCakeServlet页面
            String url = "ListCakeServlet";
            resp.sendRedirect(url);
            return;
        }

        try {
            Cake cake = CakeDB.getCake(id);
            if (cake != null) {
                // 更新库存
                CakeDB.updateStock(id, 1); // 假设每次购买一个蛋糕

                // 创建或者获得用户的Session对象
                HttpSession session = req.getSession();
                // 从Session对象中获得用户的购物车
                List<Cake> cart = (List) session.getAttribute("cart");
                if (cart == null) {
                    // 首次购买，为用户创建一个购物车(List集合模拟购物车)
                    cart = new ArrayList<>();
                    // 将购物车存入Session对象
                    session.setAttribute("cart", cart);
                }
                // 将商品放入购物车
                cart.add(cake);

                // 重定向到购物车页面
                String url = "CartServlet";
                resp.sendRedirect(url);
            } else {
                resp.getWriter().println("蛋糕不存在");
            }
        } catch (IllegalArgumentException e) {
            resp.getWriter().println(e.getMessage());
        }
    }
}

